package com.hua.api.core.util;


import com.hua.api.core.framework.util.DateUtil;

import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("all")
public class StringUtil {

    public final static String NEWLINE = "\r";
    public final static String BLANK_SPACE = " ";
    private static final String BLANK = "";
    public final static String IP1 = "x-forwarded-for";
    public final static String IP2 = "Proxy-Client-IP";
    public final static String IP3 = "WL-Proxy-Client-IP";
    public final static String UNKNOWN = "unknown";
    public final static String COMMA = ",";
    private static Long IMGSEQ = 0l;

    public static boolean isEmptys(Object...objects){
        for(Object str:objects){
            if(isEmpty(str)){
                return true;
            }
        }
        return false;
    }


    public static boolean isEmpty(String s){
        return s == null || BLANK.compareTo(s) == 0;
    }
    public static boolean isEmpty(Object str) {
        return str == null || BLANK.equals(str);
    }
    public static int getInt(String str, int defaultVal){
        if(str!=null){
            return Integer.valueOf(str);
        }
        return defaultVal;
    }

    public static String dealEmpty(String str,String def){
        return isEmpty(str) ? def:str;
    }

    public static String dealNull(String str) {
        return str != null ? str.trim() : BLANK;
    }
    public static String dealNull(Object obj) {
        String str = BLANK;
        if(obj!=null){
            if(obj instanceof String){
                str = (String)obj;
            }else{
                str = obj.toString();
            }
        }
        return str;
    }
    public static String convertHtml(String str) {
        str = (str == null) ? BLANK : str;
        str = str.replaceAll(NEWLINE, "<br/>");
        str = str.replaceAll(BLANK_SPACE, "&nbsp;");
        return str;
    }

    public static String dealNull(Object str,String defaultValue){
        return str != null ? str.toString().trim() : defaultValue;
    }

    public static String dealNull(String str, String defaultVal) {
        return str != null ? str.trim() : defaultVal;
    }
    public static String encode(String str, final String encoding) {
        try {
            if (!StringUtil.isEmpty(str)) {
                str = URLEncoder.encode(str, encoding);
            }
        } catch (Exception e) {
        }
        return str;
    }
    public static String decode(String str, final String encoding) {
        try {
            if (!StringUtil.isEmpty(str)) {
                str = URLDecoder.decode(str,encoding);
            }
        } catch (Exception e) {
        }
        return str;
    }

    public static boolean contains(String[] array,String value){
        for(String strs:array){
            if(StringUtil.equals(strs,value)){
                return true;
            }
        }
        return false;
    }

    public static boolean equals(Object value1, Object value2) {
        boolean is = false;
        if (value1 == value2) { // is null or self
            return is = true;
        }
        if (value1 != null && value2 != null) { // is not null;
            return value1.equals(value2);
        }
        return is;
    }
    public static boolean regex(String regex, String str) {
        boolean trueOrFalse;
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        trueOrFalse = m.matches();
        return trueOrFalse;
    }
    //获取后缀名
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');
            if ((i > -1) && (i < (filename.length() - 1))) {
                return filename.substring(i + 1);
            }
        }
        return null;
    }
    //获取文件名
    public static String getFileName(String filename){
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('/');
            if ((i > -1) && (i < (filename.length() - 1))) {
                return filename.substring(i + 1);
            }
        }
        return filename;
    }
    //获取文件名
    public static String getFileNameNoSuffix(String filename){
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('/');
            if ((i > -1) && (i < (filename.length() - 1))) {
                return filename.substring(i + 1);
            }
        }
        return filename.replaceAll("\\..*", "");
    }


    public static boolean createFolder(String file) {
        File folder = new File(file);
        if(!folder.exists()){
            return folder.mkdirs();
        };return true;
    }

    //上传文件
    private static void upload(File upload, String absolutePath) throws Exception {
        FileOutputStream fos = new FileOutputStream(absolutePath);
        FileInputStream fis = new FileInputStream(upload);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fis.close();
        fos.close();
    }
    public static String trim(String str){
        return StringUtil.dealNull(str).trim();
    }
    public static String subString(String str,int i){
        if(StringUtil.isEmpty(str)) return null;
        return str.length()>i?str.substring(0,i)+"...":str;
    }
    public static int random(int n){
        if(n==0) return 0;
        Random random = new Random();
        return Math.abs(random.nextInt())%n;
    }
    public static double round(double number, int bit){
        double n = Math.pow(10, bit);
        int b = (int)Math.round(number * n); //小数点后n位前移，并四舍五入
        return (double)b / n; //还原小数点后n位
    }
    public static void mkDir(String str){
        File file = new File(str);
        if(!file.exists()){
            file.mkdir();
        }
    }

    public static String currentFileName(String fileName,Long id){
        String ext = StringUtil.getExtensionName(fileName);
        IMGSEQ++;
        if(IMGSEQ>100) IMGSEQ=0l;
        return id+"_"+IMGSEQ+Long.toString(System.currentTimeMillis())+"."+ext;
    }

    public static String filterIp(String ip){
        if(StringUtil.isEmpty(ip)) return "";
        String[][] object={new String[]{"\\.\\d*\\.",".*."},new String[]{"\\.\\d*\\.",".*."}};
        return replace(ip,object);
    }
    public static String replace(final String sourceString,Object[] object) {
        String temp=sourceString;
        for(int i=0;i<object.length;i++){
            String[] result=(String[])object[i];
            Pattern    pattern = Pattern.compile(result[0]);
            Matcher matcher = pattern.matcher(temp);
            temp=matcher.replaceAll(result[1]);
        }
        return temp;
    }

    public static String fillZero(String code,Integer len){
        String s = StringUtil.dealNull(code);//code.toString();
        while(s.length()<len){
            s="0"+s;
        }
        return s;
    }
    public static InputStream getFullPathInputStream(String path){
        try {
            URL url = new URL(path);
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            return urlc.getInputStream();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    public static String createUuid(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String createId(Integer length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String createFullId(Integer length) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String format(String template, Object... params) {
        String content = template;
        if (params != null && params.length > 0) {
            try {
                content = String.format(template, params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return content;
    }


    public static String getFilePath(String filename){
        String extensionName =StringUtil.getExtensionName(filename);
        extensionName=StringUtil.dealNull(extensionName,"jpg");
        return "/local/"+DateUtil.getFormatDate(new Date(), "yyyy/MM/dd")+"/"+StringUtil.createId(32)+"."+extensionName;
    }


//    public static void main(String[] args){
//
//        String toMobile = "15173089814";
//        String phone = toMobile.substring(toMobile.length()-4);
//        System.out.println(phone);
//    }

    // ex 10.2333->10.23
    /**
     * 方法描述：TODO 四舍五入
     * @auther luoyouhua
     * exp: 10.2343-> 10.23  10.2354->10.24
     * @version 1.0
     * @datetime 2022-03-31 11:30:26
     * Copyright © 2021 xiaoke66.cn All Rights Reserved
     */
    public static double tofixed(Double value,int size){
        if(null==value){
            return 0d;
        }
        double pow = Math.pow(10,size);
        long src = Math.round(value*pow); //四舍五入
        return src/pow;
    }

    public static String matchstr(String regexp,String text){
        Pattern pattern =  Pattern.compile(regexp);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()){
            return matcher.group(1);
        }
        return text;
    }


}
